package com.blackhorse.publish_subscribe;

import com.blackhorse.utils.ConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer1 {

    public static void main(String[] args) {
        Connection connection = null;
        Channel channel = null;
        try {
            connection = ConnectionUtils.getConnection();
            channel = connection.createChannel();
            //声明交换机
            channel.exchangeDeclare(Producer.FANOUT_EXCHANGE, BuiltinExchangeType.FANOUT);
            //声明队列
            channel.queueDeclare(Producer.FANOUT_QUEUE_1, true, false, false, null);
            //队列绑定交换机
            channel.queueBind(Producer.FANOUT_QUEUE_1, Producer.FANOUT_EXCHANGE, "");
            //创建消费者；并设置消息处理
            DefaultConsumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    System.out.println("路由key为：" + envelope.getRoutingKey());
                    System.out.println("交换机为：" + envelope.getExchange());
                    System.out.println("消息id为：" + envelope.getDeliveryTag());
                    System.out.println("消费者1-接收到的消息为：" + new String(body, "utf-8"));
                }
            };
            //监听消息
            channel.basicConsume(Producer.FANOUT_QUEUE_1, true, consumer);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } finally {

        }

    }
}
